//
//  XS_HomeVC.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/5.
//

import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import ZZYQRCodeSwift
import Toast_Swift

/// 价格逻辑
/// - 会员:
///   - vipFree:     会员免费：免费、原价
///   - vipPay:      会员不免费：会员价、原价
/// - 非会员：
///   - userFree:    免费：免费、原价
///   - userPay:     不免费：优惠价、原价         vip模块:  优惠价、会员价
/// - Parameters:
///   - isFree: 是否免费
///   - vipIsFree: 会员是否免费
///   - price: 原价
///   - discountPrice: 优惠价
///   - vipPrice: 会员价
///   - isVipModule: 是否是VIP模块
/// - Returns: 显示价格、原价
public func xdGetPrice(isFree: String, vipIsFree: String, price: String, discountPrice: String, vipPrice: String, isVipModule: Bool = false) -> (showPrice: String, price: String) {
    
    let priceS = (Double(price) ?? 0) > 0 ? price : ""
    let discountPriceS = (Double(discountPrice) ?? 0) > 0 ? discountPrice : ""
    let vipPriceS = (Double(vipPrice) ?? 0) > 0 ? vipPrice : ""
    
    if isFree == "userFree" { // 免费
        return ("", priceS) // 免费、原价
    } else { // 不免费
        if let infoModel = XS_Singleton.shared.infoModel, infoModel.userBO.userType == "vip" { // 会员
            if vipIsFree == "vipFree" { // 会员免费
                return ("", priceS) // 免费、原价
            } else { // 会员不免费
                return (vipPriceS, priceS) // 会员价、原价
            }
        } else { // 非会员
            if isVipModule == true { // VIP模块
                return (discountPriceS, vipPriceS) // 优惠价、会员价
            } else { // 非VIP模块
                return (discountPriceS, priceS) // 优惠价、原价
            }
        }
    }
}

//情况0会员免费并且用户是会员，展示免费,画掉原价
//情况1是免费课的展示免费文字，画掉的是原价,
//情况2非免费课有折扣价格展示折扣价，画掉原价
//情况3没有折扣价，只展示原价,
//领取的课程也要跳转到下单页，走下流程

public func xsGetPrice(vipIsFree: String, isFree: String, vipPrice: String, discountPrice: String, price: String) -> (String, String) {
    let price = price == "0" ? "" : price
    let discountPrice = discountPrice == "0" ? "" : discountPrice

    if isFree == "userFree" {
        return ("", price)
    }
    if vipIsFree == "vipFree", let infoModel = XS_Singleton.shared.infoModel, infoModel.userBO.userType == "vip" {
        return ("", price)
    }
    if vipIsFree == "vipPay", let infoModel = XS_Singleton.shared.infoModel, infoModel.userBO.userType == "vip" {
        return (vipPrice, price)
    }
    if discountPrice.count > 0 {
        return (discountPrice, price)
    }
    return (price, "")
}


class XS_HomeTopM: XS_BaseModel {
    var id = 0
    var name = ""
    var type = ""
    var industryName = ""
    var industryType = ""
    var selected = ""
}
/// 用户在首页查看学习进度或学习计划页查看自己的课程
class XS_QueryUserCurriculumListM: XS_BaseModel {
    var id = 0 // 课程编号
    var curriculumName = "" // 课程名称
    var curriculumImgUrl = "" // 课程图片地址
    var isLastLearn = "" // 是否最近学习(最后一次观看)
    var planDay = 0 // 计划学习天数
    var lastDay = 0 // 剩余天数
    var percentage = 0 // 百分比
    var curriculumNum = "" // 课程数目

}
class XS_QueryUserCurriculumM: XS_BaseModel {
    var records: [XS_QueryUserCurriculumListM] = []
    var total = 0 // 总记录数
    var size = 10 // 每页数据量
    var current = 0 // 当前页
    var searchCount = false
    var pages = 0 // 总页数
}
/// 查询近期直播
class XS_menuItemLiveDTOListM: XS_BaseModel {
    var startState = "" // 直播开始时间 已开始则返回已开始,今天未开始则返回下午12:12这种格式, 如果不是今天的直播课 则返回开始时间(字符串)
    var liveCover = "" // 直播封面图
    var introduce = "" // 课程简介
    var reservationCount = 0 // 预定人数
    var endTime = "" // 结束时间
    var startTime = "" // 开始时间
    var title = "" // 直播标题
    var id = 0 // id

}

class XS_chapterSpecialDTOListM: XS_BaseModel {
    var id = "" // 章节编号
    var curriculumHourName = "" // "第三课",
    var chapterName = "" // 章节名称
    var count = "" // 章节课时数
    var isWatch = "" // 章节是否可试看
}

class XS_menuItemCurriculumDtoListM: XS_BaseModel {
    var id = "" // 课程编号
    var curriculumName = "" // 课程名称
    var introduce = "" // 课程简介
    var price = "" // 价格
    var discountPrice = "" // 优惠价
    var purchaseNum = "0" // 购买人数
    var curriculumForm = "" // 课程形式 线下：offline,线上：online
    var curriculumImgUrl = "" // 课程图片地址
    var offlineTime = "" // 线下课时间
    var curriculumType = "" // 课程类型 是否可拼单（拼单，together，不可以拼单noTogether）
    var curriculumNum = "" // 课程数目
    var vipIsFree = "vipFree" // 会员是否免费（是：vipFree, 否：vipPay）
    var vipPrice = "" // 会员价格
    var isFree = "" // 是否免费（是：userFree，否：userPay）
    var chapterNum = 0 // 章节数目
    var label = "" // 标签
    var offlineAddress = "" // 线下课地址
    var chapterSpecialDTOList: [XS_chapterSpecialDTOListM] = []
    var startTime = ""
    var endTime = ""
    var certificateId = 0
    var isBuy = ""
}
/// 根据条件查询栏目【李国鹏】
class XS_queryMenuItemM: XS_BaseModel {
    var id = "" // 菜单栏目编号
    var title = "" // 菜单栏目标题
    var typesetting = "" // 菜单栏目排版方式(row 一行排列 four(两个一行 四个一组) col 一列 special 专题课
    /// 菜单栏目下的课程集合
    var menuItemCurriculumDtoList: [XS_menuItemCurriculumDtoListM] = []
    var menuItemLiveDTOList: [XS_menuItemLiveDTOListM] = []
}
class XS_queryMenuItemListM: XS_BaseModel {
    var menuItemList: [XS_queryMenuItemM] = []
    var learnSchedule = XS_QueryUserCurriculumListM()
    var bannerList: [XS_QueryBannerM] = []
}

/// 查询首页金刚区
class XD_queryHomePageArea: XS_BaseModel {
    var platform = "" // 所属平台
    var typeRelation = "" // 类型关联内容
    var type = "" // 类型（内置：builtIn，自定义：selfDefinition）
    var imgUrl = "" // icon图标地址
    var areaName = "" // 金刚区名称
}

extension XS_HomeVC {
    func getMenuitemQueryHomeTop() {
        view.isUserInteractionEnabled = false
        view.makeToastActivity(.center)
        XS_NetWork.requestJson("/menuitem/queryHomeTop")
            .mapModels(type: XS_HomeTopM.self)
            .subscribe(onNext: { [weak self] models, resp in
                guard let `self` = self, resp.success else { return }
                self.channelArray = models
                self.reloadTop()
            }, onDisposed: { [weak self] in
                self?.view.hideToastActivity()
                self?.view.isUserInteractionEnabled = true
            }).disposed(by: disposeBag)
    }
}

class XS_HomeVC: XS_BaseVC {
    let 备份 = "Image may contain cartoon, illustration and screenshot备份"
    
    lazy var channelArray: [XS_HomeTopM] = []//["首页", "管理会计", "物流管理"]
    lazy var pageView = getPageView()
//    lazy var segment = getSegment()
    lazy var topScroll = XS_HitScrollView()
    lazy var line = UIView()
    
    var homeScroll: UIScrollView?
    lazy var lastSelectId = 0
    
    lazy var homePageAreaArr: [XD_queryHomePageArea] = []
    lazy var homePageAreaScroll = UIScrollView()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.unselectedItemTintColor = #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1)
    }
    
    override func upView() {
        view.addSubview(topScroll)
        
        VersionManager.checkVersion(rootVc: self)
        
        let btn11 = XS_NoHighlightBtn()
        btn11.setBackgroundImage(UIImage(named: "icon_24px_扫一扫"), for: .normal)
        btn11.frame = CGRect(x: .scale*16, y: .barHeight + .scale*10, width: .scale*24, height: .scale*24)
        view.addSubview(btn11)
        btn11.rx.tap.asDriver()
            .drive(onNext: {
//                let vc = XS_VideoFullVC()
//                vc.playerUrl = URL(string: "https://media.w3.org/2010/05/sintel/trailer.mp4")
//                XS_NVC.shared.present(vc, animated: true)
                AVCaptureSessionManager.checkAuthorizationStatusForCamera {
                    let vc = XS_QRCodeVC()
                    XS_NVC.shared.present(vc, animated: false)
                } denied: {
                    let infoDict = Bundle.main.infoDictionary
                    let appName = infoDict?["CFBundleDisplayName"] ?? "学到在线"
                    let alertController: UIAlertController = UIAlertController.init(title: "无法使用相机", message: "请在iPhone的\"设置-隐私-相机\"中\n允许\(appName)访问相机", preferredStyle: UIAlertController.Style.alert)
                    
                    let cancel: UIAlertAction = UIAlertAction.init(title: "取消", style: .cancel) { (ac) in }
                    let sure: UIAlertAction = UIAlertAction.init(title: "设置", style: .default) { (ac) in
                        let url = URL.init(string: UIApplication.openSettingsURLString)
                        if UIApplication.shared.canOpenURL(url!) {
                            UIApplication.shared.open(url!)
                        }
                    }
                    alertController.addAction(cancel)
                    alertController.addAction(sure)
                    self.present(alertController, animated: true) {  }
                }

            }).disposed(by: disposeBag)
        
        let btn12 = UIButton()
        btn12.layer.cornerRadius = .scale*16
        btn12.layer.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        btn12.frame = CGRect(x: .scale*56, y: .barHeight + .scale*6, width: .scale*304, height: .scale*32)
        view.addSubview(btn12)
        do {
            let imgV = UIImageView(image: UIImage(named: "icon_16px_搜索备份"))
            imgV.frame = CGRect(x: .scale*10, y: .scale*10, width: .scale*14, height: .scale*14)
            btn12.addSubview(imgV)
            let label = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.768627451, green: 0.7764705882, blue: 0.8039215686, alpha: 1), text: "请输入搜索的课程")
            btn12.addSubview(label)
            label.snp.makeConstraints { m in
                m.centerY.equalTo(imgV.snp.centerY)
                m.left.equalTo(imgV.snp.right).offset(.scale*8)
            }
            XS_NetWork.requestJson("/setting/querySettingByKey", parameters: ["key":"search_placeholder"])
                .subscribe(onNext: { resp in
                    guard resp.success, let text = resp.data as? String else { return }
                    label.text = text
                }).disposed(by: disposeBag)
        }
        btn12.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                let vc = XS_SearchVC()
                self?.navigationController?.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        
        let line1 = UIView(frame: CGRect(x: 0, y: .barHeight + .scale*88, width: .screenWidth, height: 1))
        line1.backgroundColor = UIColor(red: 0.90, green: 0.91, blue: 0.95, alpha: 0.6)
        view.addSubview(line1)
        
        topScroll.bounces = false
        topScroll.showsHorizontalScrollIndicator = false
        topScroll.clipsToBounds = true
        topScroll.frame = CGRect(x: 0, y: .barHeight + .scale*44, width: .scale*320, height: .scale*44)
        
        line.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        line.layer.cornerRadius = .scale
        topScroll.addSubview(line)
        
//        view.addSubview(segment)
        view.addSubview(pageView)
        
        let btn2 = XS_NoHighlightBtn()
        btn2.setBackgroundImage(UIImage(named: "icon_24px_分类"), for: .normal)
        btn2.frame = CGRect(x: .scale*335, y: .barHeight + .scale*54, width: .scale*24, height: .scale*24)
        view.addSubview(btn2)
        btn2.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                guard XS_Singleton.shared.infoModel != nil else {
                    XS_NVC.shared.toLogin(false)
                    return
                }
                let vc = XS_HangyeVC()
                vc.tags = (self?.channelArray ?? []).filter { $0.type != "nav" }
                self?.present(vc, animated: true)
            }).disposed(by: disposeBag)
        
        XS_Singleton.shared.changeHome = { [weak self] in
            self?.getMenuitemQueryHomeTop()
        }
        XS_Singleton.shared.changeHome?()
    }

    func reloadTop() {
        for view in topScroll.subviews {
            if view.isKind(of: UIButton.self) {
                view.snp.removeConstraints()
                view.removeFromSuperview()
            }
        }
        var last: UIView?
        for (index, item) in channelArray.enumerated() {
            let btn = XS_NoHighlightBtn()
            btn.setTitleColor(UIColor(red: 0.22, green: 0.24, blue: 0.25, alpha: 1.00), for: .selected)
            btn.setTitleColor(UIColor(red: 0.53, green: 0.56, blue: 0.58, alpha: 1.00), for: .normal)
            btn.titleLabel?.font = btn.isSelected ? .systemFont(ofSize: .scale * 18, weight: .semibold) : .systemFont(ofSize: .scale * 16, weight: .semibold)
            btn.setTitle("  " + item.name + "  ", for: .normal)
            btn.tag = index + 100
            btn.rx.tap.asDriver()
                .drive(onNext: { [weak self] in
                    self?.pageView.changeToItem(at: index)
                    self?.didScroll(to: index)
                }).disposed(by: disposeBag)
            topScroll.addSubview(btn)
            btn.snp.makeConstraints { m in
                m.top.height.equalToSuperview()
                if let last = last {
                    m.left.equalTo(last.snp.right)
                } else {
                    m.left.equalTo(.scale*10)
                    btn.isSelected = true
                }
                m.right.lessThanOrEqualToSuperview()
            }
            last = btn
        }
        pageView.removeAll()
        pageView.reloadData()
        
        let index = channelArray.firstIndex { [weak self] in $0.id == self?.lastSelectId } ?? 0
        if channelArray.count > index {
            pageView.changeToItem(at: index)
        }
        line.frame = CGRect(x: .scale*16, y: .scale*41, width: .scale*33, height: .scale*3)
        topScroll.layoutIfNeeded()
        topScroll.layoutSubviews()
        didScroll(to: index)
    }
    
}

extension XS_HomeVC: JXSegmentDelegate,JXPageViewDataSource,JXPageViewDelegate {
    
//    func getSegment() -> JXSegment {
//        let segment = JXSegment(frame: CGRect(x: 0, y: .barHeight + 44, width: 200, height: 40))
//        segment.scrollView.contentInsetAdjustmentBehavior = .never
//        segment.updateChannels(channelArray)
//        return segment
//    }
    
    func getPageView() -> JXPageView {
        let pageView = JXPageView(frame: CGRect(x: 0, y: .barHeight + .scale*90, width: .screenWidth, height: .screenHeight - .barHeight - .scale*90 - 49 - .bottomHeight))
        pageView.scrollview.contentInsetAdjustmentBehavior = .never
        pageView.datasource = self
        pageView.delegate = self
        return pageView
    }
    
    
    func jxSegment(_ segment: JXSegment!, didSelect index: Int) {
        pageView.changeToItem(at: index)
    }
    
    func numberOfItem(in pageView: JXPageView!) -> Int {
        channelArray.count
    }
    
    func pageView(_ pageView: JXPageView!, viewAt index: Int) -> UIView! {
        if index == 0, let scroll = homeScroll {
            return scroll
        }
        let scroll = UIScrollView()
//        scroll.frame = pageView.bounds
        scroll.bounces = true
        scroll.contentInsetAdjustmentBehavior = .never
        
        let mj_header = MJRefreshNormalHeader()
        mj_header.tag = 1024
        scroll.mj_header = mj_header
        mj_header.rx.refresh
            .subscribe(onNext: { [weak self] state in
                guard let `self` = self, state == .refreshing else { return }
                self.getMenuitemQueryHomeTop()
            }).disposed(by: disposeBag)
        reload(scroll, index: index, mj_header: mj_header)
        return scroll
    }
    func reload(_ scroll: UIScrollView, index: Int, mj_header: MJRefreshNormalHeader) {
//        if index == 0 {
//            if homeScroll == nil {
//                homeScroll = scroll
//            } else {
//                getMenuitemQueryHomeTop()
//            }
//        }
        let model = channelArray[index]
        XS_NetWork.requestJson("/menuitem/queryMenuItem", parameters: ["relation":model.id,"relationType":model.type])
            .mapModel(type: XS_queryMenuItemListM.self)
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self, resp.success, let model = model else { return }
                scroll.removeSubviews([1024])
                var height = .scale*24
                if model.bannerList.count > 0 {
                    let cycle = XS_CyclePagerView(frame: CGRect(x: .scale*16, y: .scale*16, width: .scale*343, height: .scale*152))
                    cycle.layer.cornerRadius = .scale*4
                    cycle.clipsToBounds = true
                    scroll.addSubview(cycle)
                    cycle.data = model.bannerList
                    cycle.reloadData()
                    height = .scale*(16 + 152 + 24)
                }
                if index == 0 {
                    XS_NetWork.requestJson("/homePageArea/queryHomePageAreaApi", parameters: ["platform":"APP"])
                        .mapModels(type: XD_queryHomePageArea.self)
                        .subscribe(onNext: { [weak self] pageAreaModel, resp in
                            guard let `self` = self else { return }
                            self.homePageAreaArr.removeAll()
                            self.homePageAreaArr.append(contentsOf: pageAreaModel)
                            if self.homePageAreaArr.count > 0 {
                                self.reLoadBanner(scroll, top: &height, dataModels: self.homePageAreaArr)
                            }
                        }).disposed(by: self.disposeBag)
                    self.loadBanner(scroll, top: &height)
                    if model.learnSchedule.isLastLearn == "yes" {
                        self.loadProgress(scroll, top: &height, item: model.learnSchedule)
                    }
                }
                for model in model.menuItemList {
                    switch model.typesetting {
                    case "live": // 一行排列
                        if model.menuItemLiveDTOList.count > 0 {
                            self.loadJinqi(scroll, top: &height, item: model)
                        }
                    case "four": // 两个一行 四个一组
//                        self.loadMianfei(scroll, top: &height)
                        if model.menuItemCurriculumDtoList.count > 0 {
                            self.loadHuiyuan(scroll, top: &height, item: model)
                        }
                    case "col": // 一列
                        if model.menuItemCurriculumDtoList.count > 0 {
                            self.loadXianxia(scroll, top: &height, item: model)
                        }
                    case "special": // 专题课
                        if model.menuItemCurriculumDtoList.count > 0 {
                            self.loadZhuanti(scroll, top: &height, item: model)
                        }
                    default: break
                    }
                }
                scroll.contentSize = CGSize(width: 0, height: height)
            }, onDisposed: {
                mj_header.endRefreshing()
            }).disposed(by: disposeBag)
    }
    
    func didScroll(to index: Int) {
        lastSelectId = channelArray[index].id
//        segment.didChenge(to: index)
        for view in topScroll.subviews {
            if let btn = view as? UIButton {
                btn.layoutIfNeeded()
                if btn.tag == 100 + index {
                    btn.isSelected = true
                    line.center.x = btn.center.x
                } else {
                    btn.isSelected = false
                }
            }
        }
    }
}

extension XS_HomeVC {
    func getMore() -> UIButton {
        let more = XS_NoHighlightBtn()
        more.setTitle("更多", for: .normal)
        more.setImage(UIImage.init(named: "icon_12px_更多"), for: .normal)
        more.titleEdgeInsets = UIEdgeInsets(top: 0, left: -.scale * 12, bottom: 0, right: .scale * 12)
        more.imageEdgeInsets = UIEdgeInsets(top: 0, left: .scale * 14 * 2, bottom: 0, right: -.scale * 14 * 2)
        more.setTitleColor(#colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), for: .normal)
        more.titleLabel?.font = .xsFont(name: .regular, .scale*14)
        more.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                guard XS_Singleton.shared.infoModel != nil else {
                    XS_NVC.shared.toLogin()
                    return
                }
                self?.navigationController?.pushViewController(XS_FenleiVC(), animated: true)
            }).disposed(by: disposeBag)
        return more
    }
    func loadXianxia(_ scroll: UIScrollView, top: inout CGFloat, item: XS_queryMenuItemM) {
        let label = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: item.title)
        scroll.addSubview(label)
        label.snp.makeConstraints {
            $0.top.equalTo(top)
            $0.left.equalTo(.scale*16)
        }
        let more = getMore()
        scroll.addSubview(more)
        more.snp.makeConstraints({
            $0.top.bottom.equalTo(label)
            $0.right.equalTo(scroll.snp.left).offset(.screenWidth - .scale*16)
        })
        
        
        top += .scale*40
        for (_, item) in item.menuItemCurriculumDtoList.enumerated() {
            let view = item.curriculumForm == "online" ? getXianShang(item) : getXianxia(item)
            view.frame = CGRect(x: .scale*16, y: top, width: .scale*343, height: .scale*88)
            scroll.addSubview(view)
            top += .scale*88 + .scale*16
        }
//        top += .scale*24
    }
    func getXianxia(_ item: XS_menuItemCurriculumDtoListM) -> UIView {
        let view = UIView()
        let tap = UITapGestureRecognizer()
        view.addGestureRecognizer(tap)
        tap.rx.event.asDriver()
            .drive(onNext: { _ in
                let vc = XS_KCXianxiaVC()
                vc.id = item.id
                XS_NVC.shared.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        
        let imgV = UIImageView()
        imgV.frame = CGRect(x: 0, y: 0, width: .scale*112, height: .scale*80)
        view.addSubview(imgV)
        imgV.layer.cornerRadius = .scale*4
        imgV.clipsToBounds = true
        imgV.sd_setImage(with: URL(string: item.curriculumImgUrl))
        
        if let infoModel = XS_Singleton.shared.infoModel, infoModel.userBO.userType == "user", (Double(item.vipPrice) ?? 0) <= 0, (Double(item.discountPrice) ?? 0) <= 0 {
            let tagsView = UIView(frame: CGRect(x: 0, y: 0, width: 49, height: 18) * .scale)
            imgV.addSubview(tagsView)
            let sLayer = CAShapeLayer()
            sLayer.fillColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
            sLayer.path = UIBezierPath(roundedRect: tagsView.bounds, byRoundingCorners: [.bottomRight], cornerRadii: CGSize(width: 4, height: 4) * .scale).cgPath
            tagsView.layer.addSublayer(sLayer)
            let tagLabel = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), alignment: .center, text: "限时免费")
            tagsView.addSubview(tagLabel)
            tagLabel.snp.makeConstraints({
                $0.center.equalToSuperview()
            })
        } else if (Double(item.vipPrice) ?? 0) <= 0, (Double(item.discountPrice) ?? 0) > 0 {
            let layerView = UIView()
            layerView.frame = CGRect(x: 0, y: 0, width: .scale*45, height: .scale*18)
            layerView.corner(byRoundingCorners: .bottomRight, radii: .scale*4)
            layerView.alpha = 1
            // fillCode
            let bglayer1 = CAGradientLayer()
            bglayer1.colors = [UIColor(red: 1, green: 0.91, blue: 0.73, alpha: 1).cgColor, UIColor(red: 0.98, green: 0.84, blue: 0.59, alpha: 1).cgColor]
            bglayer1.locations = [0, 1]
            bglayer1.frame = layerView.bounds
            layerView.layer.addSublayer(bglayer1)
            bglayer1.startPoint = CGPoint(x: 1.00, y: 0.50)
            bglayer1.endPoint = CGPoint(x: -0.00, y: 0.50)
            imgV.addSubview(layerView)
            
            let label = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 0.5803921569, green: 0.3490196078, blue: 0, alpha: 1), text: "VIP免费")
            layerView.addSubview(label)
            label.snp.makeConstraints({
                $0.center.equalToSuperview()
            })
        }
        
        let label1 = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: item.curriculumName)
        view.addSubview(label1)
        label1.snp.makeConstraints {
            $0.top.equalToSuperview()
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        let icon = UIImageView(image: UIImage(named: "icon_12px_定位"))
        view.addSubview(icon)
        icon.snp.makeConstraints { (make) in
            make.top.equalTo(label1.snp.bottom).offset(.scale * 5)
            make.left.equalTo(label1)
            make.width.height.equalTo(.scale * 12)
        }
        let label2 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), text: item.offlineAddress)
        view.addSubview(label2)
        label2.snp.makeConstraints {
            $0.centerY.equalTo(icon.snp.centerY)
            $0.left.equalTo(icon.snp.right).offset(.scale*4)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        
        let (p, _) = xsGetPrice(vipIsFree: item.vipIsFree, isFree: item.isFree, vipPrice: item.vipPrice, discountPrice: item.discountPrice, price: item.price)
        var dateTime = ""
        let fm = DateFormatter()
        fm.dateFormat = "yyyy-MM-dd HH:mm:ss"
        if let date = fm.date(from: item.startTime) {
            let fm1 = DateFormatter()
            fm1.dateFormat = "MM-dd"
            dateTime = fm1.string(from: date)
        }
        let text = NSMutableAttributedString.init(string: dateTime)
        if p.count > 0 {
            let attr = NSMutableAttributedString(string: " | ￥")
            text.append(attr)
        }
        do {
            let attr = NSMutableAttributedString(string: p.count > 0 ? p : " | 免费")
            text.append(attr)
        }
        text.yy_font = .xsFont(name: .medium, .scale*12)
        text.yy_color = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
        text.yy_alignment = .right
        let label4 = UILabel()
        label4.attributedText = text
        view.addSubview(label4)
        label4.snp.makeConstraints({
            $0.right.equalToSuperview()
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.bottom.equalTo(imgV.snp.bottom)
        })
        
        let line = UIView()
        line.backgroundColor = #colorLiteral(red: 0.9019607843, green: 0.9137254902, blue: 0.9450980392, alpha: 1)
        view.addSubview(line)
        line.snp.makeConstraints({
            $0.left.bottom.right.equalToSuperview()
            $0.height.equalTo(1)
        })
        
        return view
    }
    
    func getXianShang(_ item: XS_menuItemCurriculumDtoListM) -> UIView {
        let view = UIView()
        let tap = UITapGestureRecognizer()
        view.addGestureRecognizer(tap)
        tap.rx.event.asDriver()
            .drive(onNext: { _ in
                let vc = item.curriculumForm == "online" ? XS_KeChengVC() : XS_KCXianxiaVC()
                vc.id = item.id
                XS_NVC.shared.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        
        let imgV = UIImageView()
        imgV.layer.cornerRadius = .scale*4
        imgV.layer.masksToBounds = true
        view.addSubview(imgV)
        imgV.snp.makeConstraints({
            $0.width.equalTo(.scale*112)
            $0.height.equalTo(.scale*80)
            $0.left.equalToSuperview()
            $0.top.equalToSuperview()
        })
            
        let label = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1))
        view.addSubview(label)
        label.snp.makeConstraints({
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.top.equalToSuperview()
            $0.right.lessThanOrEqualToSuperview()
        })
        
        let people = UILabel.xsLabel(size: .scale*13, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1))
        view.addSubview(people)
        people.snp.makeConstraints({
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.bottom.equalTo(imgV)
        })
        
        let price = UILabel.xsLabel(size: .scale*13, fontName: .semibold, color: #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1))
        view.addSubview(price)
        price.snp.makeConstraints({
            $0.right.equalToSuperview()
            $0.bottom.equalTo(imgV)
        })
        
//        let line = UIView()
//        line.backgroundColor = #colorLiteral(red: 0.9019607843, green: 0.9137254902, blue: 0.9450980392, alpha: 1)
//        view.addSubview(line)
//        line.snp.makeConstraints({
//            $0.left.bottom.right.equalToSuperview()
//            $0.height.equalTo(1)
//        })
        
        if let infoModel = XS_Singleton.shared.infoModel, infoModel.userBO.userType == "user", (Double(item.vipPrice) ?? 0) <= 0, (Double(item.discountPrice) ?? 0) <= 0 {
            let tagsView = UIView(frame: CGRect(x: 0, y: 0, width: 49, height: 18) * .scale)
            imgV.addSubview(tagsView)
            let sLayer = CAShapeLayer()
            sLayer.fillColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
            sLayer.path = UIBezierPath(roundedRect: tagsView.bounds, byRoundingCorners: [.bottomRight], cornerRadii: CGSize(width: 4, height: 4) * .scale).cgPath
            tagsView.layer.addSublayer(sLayer)
            let tagLabel = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), alignment: .center, text: "限时免费")
            tagsView.addSubview(tagLabel)
            tagLabel.snp.makeConstraints({
                $0.center.equalToSuperview()
            })
        } else if (Double(item.vipPrice) ?? 0) <= 0, (Double(item.discountPrice) ?? 0) > 0  {
            let layerView = UIView()
            layerView.frame = CGRect(x: 0, y: 0, width: .scale*45, height: .scale*18)
            layerView.corner(byRoundingCorners: .bottomRight, radii: .scale*4)
            layerView.alpha = 1
            // fillCode
            let bglayer1 = CAGradientLayer()
            bglayer1.colors = [UIColor(red: 1, green: 0.91, blue: 0.73, alpha: 1).cgColor, UIColor(red: 0.98, green: 0.84, blue: 0.59, alpha: 1).cgColor]
            bglayer1.locations = [0, 1]
            bglayer1.frame = layerView.bounds
            layerView.layer.addSublayer(bglayer1)
            bglayer1.startPoint = CGPoint(x: 1.00, y: 0.50)
            bglayer1.endPoint = CGPoint(x: -0.00, y: 0.50)
            imgV.addSubview(layerView)
            
            let label = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 0.5803921569, green: 0.3490196078, blue: 0, alpha: 1), text: "VIP免费")
            layerView.addSubview(label)
            label.snp.makeConstraints({
                $0.center.equalToSuperview()
            })
        }
        
        let (p, _) = xsGetPrice(vipIsFree: item.vipIsFree, isFree: item.isFree, vipPrice: item.vipPrice, discountPrice: item.discountPrice, price: item.price)
        imgV.sd_setImage(with: URL(string: item.curriculumImgUrl))
        label.text = item.curriculumName
        people.text = "\(item.purchaseNum)人加入学习"
        price.text = "共\(item.curriculumNum)节 | " + ((p.count > 0 && (Double(p) ?? 0) > 0) ? "￥\(p)" : "免费")

        var lastV: UIView?
        for text in (item.label.components(separatedBy: ",")) {
            let tagV = getTags(text)
            view.addSubview(tagV)
            tagV.snp.makeConstraints { (make) in
                make.top.equalTo(label.snp.bottom).offset(.scale * 5)
                make.height.equalTo(.scale * 16)
                if let last = lastV {
                    make.left.equalTo(last.snp.right).offset(.scale * 6)
                } else {
                    make.left.equalTo(imgV.snp.right).offset(.scale * 12)
                }
            }
            lastV = tagV
        }
        
        return view
    }
    
    func getTags(_ text: String) -> UIView {
        let tabBgV = UIView()
        tabBgV.layer.borderWidth = 0.5
        tabBgV.layer.borderColor = UIColor(red: 0.16, green: 0.74, blue: 0.61, alpha: 1.00).cgColor
        tabBgV.layer.cornerRadius = .scale * 4
        
        let tagLab = UILabel.xsLabel(size: .scale * 10, color:UIColor(red: 0.16, green: 0.74, blue: 0.61, alpha: 1.00), alignment: .center, text: text)
        tabBgV.addSubview(tagLab)
        tagLab.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.right.equalTo(-.scale * 5)
            make.left.equalTo(.scale * 5)
        }
        
        return tabBgV
    }
    
    
    func loadHuiyuan(_ scroll: UIScrollView, top: inout CGFloat, item: XS_queryMenuItemM) {
        let label = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: item.title)
        scroll.addSubview(label)
        label.snp.makeConstraints {
            $0.top.equalTo(top)
            $0.left.equalTo(.scale*16)
        }
        let more = getMore()
        scroll.addSubview(more)
        more.snp.makeConstraints({
            $0.top.bottom.equalTo(label)
            $0.right.equalTo(scroll.snp.left).offset(.screenWidth - .scale*16)
        })
        
        top += .scale*24 - .scale*196
        for (index, item) in item.menuItemCurriculumDtoList.enumerated() {
            if index%2 == 0 {
                top += .scale*196 + .scale*16
            }
            let view = getHuiyuan(item)
            view.frame = CGRect(x: index%2 == 0 ? .scale*16 : .scale*196, y: top, width: .scale*164, height: .scale*196)
            scroll.addSubview(view)
        }
        
        top += .scale*196 + .scale*24
    }
    func getHuiyuan(_ item: XS_menuItemCurriculumDtoListM) -> UIView {
        let view = UIView()
        view.layer.corner(radius: .scale*4, bgColor: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), isShadow: true, sColor: #colorLiteral(red: 0.1843137255, green: 0.2039215686, blue: 0.2039215686, alpha: 1), offset: CGSize(width: 0, height: .scale*2), effect: .scale*12, opacity: 0.06)
        let tap = UITapGestureRecognizer()
        view.addGestureRecognizer(tap)
        tap.rx.event.asDriver()
            .drive(onNext: { _ in
                let vc = item.curriculumForm == "online" ? XS_KeChengVC() : XS_KCXianxiaVC()
                vc.id = item.id
                XS_NVC.shared.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        
        let imgV = UIImageView()
        imgV.frame = CGRect(x: 0, y: 0, width: .scale*164, height: .scale*116)
        view.addSubview(imgV)
        imgV.corner(byRoundingCorners: [.topLeft, .topRight], radii: .scale*4)
        imgV.clipsToBounds = true
        imgV.sd_setImage(with: URL(string: item.curriculumImgUrl))
        
        if (Double(item.vipPrice) ?? 0) <= 0, (Double(item.discountPrice) ?? 0) > 0 {
            let layerView = UIView()
            layerView.frame = CGRect(x: 0, y: 0, width: .scale*45, height: .scale*18)
            layerView.corner(byRoundingCorners: .bottomRight, radii: .scale*4)
            layerView.alpha = 1
            // fillCode
            let bglayer1 = CAGradientLayer()
            bglayer1.colors = [UIColor(red: 1, green: 0.91, blue: 0.73, alpha: 1).cgColor, UIColor(red: 0.98, green: 0.84, blue: 0.59, alpha: 1).cgColor]
            bglayer1.locations = [0, 1]
            bglayer1.frame = layerView.bounds
            layerView.layer.addSublayer(bglayer1)
            bglayer1.startPoint = CGPoint(x: 1.00, y: 0.50)
            bglayer1.endPoint = CGPoint(x: -0.00, y: 0.50)
            imgV.addSubview(layerView)
            
            let label = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 0.5803921569, green: 0.3490196078, blue: 0, alpha: 1), text: "VIP免费")
            layerView.addSubview(label)
            label.snp.makeConstraints({
                $0.center.equalToSuperview()
            })
        }
        
        let label1 = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: item.curriculumName)
        view.addSubview(label1)
        label1.snp.makeConstraints {
            $0.top.equalTo(imgV.snp.bottom).offset(.scale*8)
            $0.left.equalTo(.scale*8)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        let label2 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: "\(item.purchaseNum)人加入学习")
        view.addSubview(label2)
        label2.snp.makeConstraints {
            $0.top.equalTo(label1.snp.bottom).offset(.scale*6)
            $0.left.equalTo(.scale*8)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
    
        let label3 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: UIColor(red: 0.67, green: 0.69, blue: 0.72, alpha: 1.00), text: "共\(item.curriculumNum)节")
        view.addSubview(label3)
        label3.snp.makeConstraints {
            $0.bottom.equalTo(-.scale*8)
            $0.left.equalTo(.scale*8)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        
        let (p, _) = xsGetPrice(vipIsFree: item.vipIsFree, isFree: item.isFree, vipPrice: item.vipPrice, discountPrice: item.discountPrice, price: item.price)
        let priceAttStr = NSMutableAttributedString.init(string: "￥\(p)")
        priceAttStr.addAttributes([.font : UIFont.systemFont(ofSize: .scale * 12, weight: .medium)], range: NSRange.init(location: 0, length: 1))
        let priceLab = UILabel.xsLabel(size: .scale * 16, fontName: .medium, color: UIColor(red: 0.93, green: 0.40, blue: 0.25, alpha: 1.00), alignment: .right)
        priceLab.attributedText = p.count > 0 ? priceAttStr : NSMutableAttributedString.init(string: "免费", attributes: [.font : UIFont.systemFont(ofSize: .scale * 15, weight: .medium)])
        view.addSubview(priceLab)
        priceLab.snp.makeConstraints { (make) in
            make.bottom.equalTo(-.scale * 8)
            make.right.equalTo(-.scale * 8)
        }
        
        return view
    }
    
        
    func loadZhuanti(_ scroll: UIScrollView, top: inout CGFloat, item: XS_queryMenuItemM) {
        let label = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: item.title)
        scroll.addSubview(label)
        label.snp.makeConstraints {
            $0.top.equalTo(top)
            $0.left.equalTo(.scale*16)
        }
        let more = getMore()
        scroll.addSubview(more)
        more.snp.makeConstraints({
            $0.top.bottom.equalTo(label)
            $0.right.equalTo(scroll.snp.left).offset(.screenWidth - .scale*16)
        })
        
        top += .scale*37
        for item in item.menuItemCurriculumDtoList {
            let view = getZhuanti(item)
            view.frame = CGRect(x: .scale*16, y: top, width: .scale*343, height: .scale*299)
            scroll.addSubview(view)
            top += .scale*299 + .scale*16
        }
        
//        top += .scale*24
    }
    func getZhuanti(_ item: XS_menuItemCurriculumDtoListM) -> UIView {
        let view = UIView()
        view.layer.corner(radius: .scale*4, bgColor: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), isShadow: true, sColor: #colorLiteral(red: 0.1843137255, green: 0.2039215686, blue: 0.2039215686, alpha: 1), offset: CGSize(width: 0, height: .scale*2), effect: .scale*12, opacity: 0.06)
        let tap = UITapGestureRecognizer()
        view.addGestureRecognizer(tap)
        tap.rx.event.asDriver()
            .drive(onNext: { _ in
                let vc = item.curriculumForm == "online" ? XS_KeChengVC() : XS_KCXianxiaVC()
                vc.id = item.id
                XS_NVC.shared.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        let contentView = UIView()
        contentView.layer.cornerRadius = .scale*4
        contentView.layer.masksToBounds = true
        view.addSubview(contentView)
        contentView.snp.makeConstraints { $0.edges.equalToSuperview() }
        let imgV = UIImageView()
        imgV.sd_setImage(with: URL(string: item.curriculumImgUrl))
        imgV.contentMode = .scaleAspectFill
        imgV.clipsToBounds = true
        contentView.addSubview(imgV)
        imgV.snp.makeConstraints { m in
            m.left.right.top.equalToSuperview()
            m.height.equalTo(.scale*128)
        }
        let icon = UIImageView(image: UIImage(named: "编组 39"))
        view.addSubview(icon)
        icon.snp.makeConstraints { m in
            m.width.equalTo(.scale*43)
            m.height.equalTo(.scale*49)
            m.top.equalTo(-.scale*5)
            m.right.equalTo(-.scale*10)
        }
        if item.certificateId == 0 {
            icon.isHidden = true
        }
        
//        let nLab = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), text: item.curriculumName)
//        contentView.addSubview(nLab)
//        nLab.snp.makeConstraints { m in
//            m.left.top.equalTo(.scale*12)
//        }
        let cLab = UILabel.xsLabel(size: .scale*14, fontName: .regular, color: #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), text: "\(item.purchaseNum)人加入学习")
        contentView.addSubview(cLab)
        cLab.snp.makeConstraints { m in
            m.left.equalTo(.scale*12)
//            m.top.equalTo(nLab.snp.bottom).offset(.scale*6)
            m.bottom.equalTo(imgV.snp.bottom).offset(-.scale * 13)
        }
        let btn = XS_NoHighlightBtn()
        btn.layer.cornerRadius = .scale*12
        btn.layer.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.19)
        btn.setTitle("  \(item.chapterNum)步骤 | \(item.curriculumNum)门课  ＞  ", for:.normal)
        btn.setTitleColor(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
        btn.titleLabel?.font = .xsFont(name: .regular, .scale*12)
        contentView.addSubview(btn)
        btn.snp.makeConstraints { m in
            m.height.equalTo(.scale*23)
            m.right.equalTo(-.scale*12)
            m.bottom.equalTo(imgV.snp.bottom).offset(-.scale*13)
        }
        
        let buy = XS_NoHighlightBtn()
        buy.isUserInteractionEnabled = false
        buy.layer.cornerRadius = .scale*16
        buy.layer.backgroundColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
        buy.setTitle("立即购买", for: .normal)
        buy.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
        buy.titleLabel?.font = .xsFont(name: .regular, .scale*13)
        buy.isHidden = item.isBuy == "yes"
        contentView.addSubview(buy)
        buy.snp.makeConstraints { m in
            m.height.equalTo(.scale*32)
            m.width.equalTo(.scale*77)
            m.right.equalTo(-.scale*12)
            m.bottom.equalTo(-.scale*16)
        }
        buy.rx.tap.asDriver()
            .drive(onNext: {
                guard XS_Singleton.shared.infoModel != nil else {
                    XS_NVC.shared.toLogin(false)
                    return
                }
                let buyVC = XS_BuyVC()
                buyVC.courseId = "\(item.id)"
                buyVC.courseClassification = "online"
                XS_NVC.shared.pushViewController(buyVC, animated: true)
            }).disposed(by: disposeBag)
        
        let pLab = UILabel()
        contentView.addSubview(pLab)
        pLab.snp.makeConstraints { m in
            m.left.equalTo(.scale*12)
            m.bottom.equalTo(-.scale*16)
        }
        let (p, dp) = xsGetPrice(vipIsFree: item.vipIsFree, isFree: item.isFree, vipPrice: item.vipPrice, discountPrice: item.discountPrice, price: item.price)
        do {
            let text = NSMutableAttributedString()
            if p.count > 0 {
                let text1 = NSMutableAttributedString(string: "￥")
                text1.yy_font = .xsFont(name: .medium, .scale*14)
                text.append(text1)
            }
            let text2 = NSMutableAttributedString(string: p.count > 0 ? p : "免费")
            text2.yy_font = .xsFont(name: .semibold, .scale*18)
            text.append(text2)
            text.yy_color = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
            pLab.attributedText = text
        }
        
        let dLab = UILabel()
        contentView.addSubview(dLab)
        dLab.snp.makeConstraints { m in
            m.left.equalTo(pLab.snp.right).offset(.scale*4)
            m.centerY.equalTo(pLab.snp.centerY)
        }
        if dp.count > 0 {
            let text = NSMutableAttributedString(string: "原价\(dp)")
            text.yy_strikethroughStyle = .single
            text.yy_strikethroughColor = #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1)
            text.yy_color = #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1)
            text.yy_font = .xsFont(name: .regular, .scale*12)
            dLab.attributedText = text
        }
        
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        flowLayout.itemSize = CGSize(width: .scale*164, height: .scale*95)
        flowLayout.minimumLineSpacing = .scale*12
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: .scale*12, bottom: 0, right: .scale*12)
        let collection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collection.bounces = false
        collection.showsVerticalScrollIndicator = false
        collection.showsHorizontalScrollIndicator = false
        collection.backgroundColor = .clear
        contentView.addSubview(collection)
        collection.snp.makeConstraints { (m) in
            m.left.right.equalToSuperview()
            m.height.equalTo(.scale*96)
            m.top.equalTo(imgV.snp.bottom).offset(.scale*12)
        }
        
        collection.register(XS_ExclusivePlanCell.self, forCellWithReuseIdentifier: "cell")
        let dataSource = RxCollectionViewSectionedReloadDataSource<XS_ExclusivePlanVC.Section>(configureCell: { ds, cv, ip, it in
            let cell = cv.dequeueReusableCell(withReuseIdentifier: "cell", for: ip) as! XS_ExclusivePlanCell
            cell.model.onNext(it)
            return cell
        })
        
        Driver.of([XS_ExclusivePlanVC.Section(model: "", items: item.chapterSpecialDTOList)])
            .drive(collection.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
        
        collection.rx.modelSelected(String.self)
            .asDriver()
            .drive(onNext: { item in
                
            }).disposed(by: disposeBag)
        
        return view
    }
    
    
    func loadMianfei(_ scroll: UIScrollView, top: inout CGFloat) {
        let label = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: "免费好课")
        scroll.addSubview(label)
        label.snp.makeConstraints {
            $0.top.equalTo(top)
            $0.left.equalTo(.scale*16)
        }
        let more = getMore()
        scroll.addSubview(more)
        more.snp.makeConstraints({
            $0.top.bottom.equalTo(label)
            $0.right.equalTo(scroll.snp.left).offset(.screenWidth - .scale*16)
        })
        
        var last = top + .scale*40 - .scale*16
        for index in 0..<4 {
            let view = getMianfei()
            view.frame = CGRect(x: index%2 == 0 ? .scale*16 : .scale*196, y: top + .scale*40 + CGFloat(index/2)*(.scale*16 + .scale*196), width: .scale*164, height: .scale*196)
            scroll.addSubview(view)
            
            if index%2 == 0 {
                last += .scale*16 + .scale*196
            }
        }
        
        top = last + .scale*40
    }
    func getMianfei() -> UIView {
        let view = UIView()
        view.layer.corner(radius: .scale*4, bgColor: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), isShadow: true, sColor: #colorLiteral(red: 0.1843137255, green: 0.2039215686, blue: 0.2039215686, alpha: 1), offset: CGSize(width: 0, height: .scale*2), effect: .scale*12, opacity: 0.06)
        
        let imgV = UIImageView()
        imgV.image = UIImage(named: 备份)
        imgV.frame = CGRect(x: 0, y: 0, width: .scale*164, height: .scale*116)
        view.addSubview(imgV)
        
        let label1 = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: "可视化程序设计及应用")
        view.addSubview(label1)
        label1.snp.makeConstraints {
            $0.top.equalTo(imgV.snp.bottom).offset(.scale*8)
            $0.left.equalTo(.scale*8)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        let label2 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: "1242人加入学习")
        view.addSubview(label2)
        label2.snp.makeConstraints {
            $0.top.equalTo(label1.snp.bottom).offset(.scale*6)
            $0.left.equalTo(.scale*8)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        let label3 = UILabel.xsLabel(size: .scale*12, fontName: .semibold, color: #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1), text: "共9节 | 免费")
        view.addSubview(label3)
        label3.snp.makeConstraints {
            $0.bottom.equalTo(-.scale*8)
            $0.left.equalTo(.scale*8)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        
        return view
    }
    
    func loadJinqi(_ scroll: UIScrollView, top: inout CGFloat, item: XS_queryMenuItemM) {
        let label = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: item.title)
        scroll.addSubview(label)
        label.snp.makeConstraints {
            $0.top.equalTo(top)
            $0.left.equalTo(.scale*16)
        }
//        let more = getMore()
//        scroll.addSubview(more)
//        more.snp.makeConstraints({
//            $0.top.bottom.equalTo(label)
//            $0.right.equalTo(scroll.snp.left).offset(.screenWidth - .scale*16)
//        })
        
        let s = UIScrollView()
        s.bounces = false
        s.showsHorizontalScrollIndicator = false
        s.contentInsetAdjustmentBehavior = .never
        s.frame = CGRect(x: 0, y: .scale*39 + top, width: .screenWidth, height: .scale*84)
        scroll.addSubview(s)
        
        for (index, item) in item.menuItemLiveDTOList.enumerated() {
            let view = getJinqi(item)
            s.addSubview(view)
            view.snp.makeConstraints {
                $0.top.height.equalToSuperview()
                $0.width.equalTo(.scale*320)
                $0.left.equalTo(CGFloat(index) * .scale*320)
                $0.right.lessThanOrEqualToSuperview()
            }
        }
        // 条目的高度加上下面间隔
        top = top + .scale*39 + .scale*84 + .scale*21
    }
    func getJinqi(_ item: XS_menuItemLiveDTOListM) -> UIView {
        let view = UIView()
        let tap = UITapGestureRecognizer()
        view.addGestureRecognizer(tap)
        tap.rx.event.asDriver()
            .drive(onNext: { _ in
                let vc = XS_KCZhiboVC()
                vc.id = "\(item.id)"
                XS_NVC.shared.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        
        let imgV = UIImageView()
        imgV.sd_setImage(with: URL(string: item.liveCover))
        imgV.frame = CGRect(x: .scale*16, y: 0, width: .scale*112, height: .scale*80)
        view.addSubview(imgV)
        imgV.layer.cornerRadius = .scale*4
        imgV.layer.masksToBounds = true
        
//        let fm = DateFormatter()
//        fm.dateFormat = "yyyy-MM-dd HH:mm:ss.sss+00:00"
        let label = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), alignment: .center)
        label.layer.cornerRadius = .scale * 4
        imgV.addSubview(label)
        label.snp.makeConstraints({
            $0.height.equalTo(.scale*18)
            $0.top.left.equalToSuperview()
        })
        
//        if item.startState.hasPrefix("20") {
//            label.isHidden = true
//        } else
        if item.startState == "已开始" {
            label.text = " 已开始 "
            label.layer.backgroundColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
        } else {
            label.text = " \(item.startState) "
            label.layer.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        }
        
//        if let dateS = fm.date(from: item.startTime.replacingOccurrences(of: "T", with: " ")) {
//            let date = Date()
//            if date >= dateS {
//                label.text = " 已开始   "
//                label.layer.backgroundColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
//            } else {
//                let calendar = Calendar.current
//                if calendar.isDateInToday(dateS) {
//                    fm.dateFormat = "HH:mm"
//                    label.text = " 今天 \(fm.string(from: dateS))   "
//                    label.layer.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
//                }
//            }
//        }
        label.layoutIfNeeded()
        label.corner(byRoundingCorners: [.bottomRight], radii: .scale*4)
        
        let label1 = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: item.title)
        view.addSubview(label1)
        label1.snp.makeConstraints {
            $0.top.equalTo(.scale*1)
            $0.left.equalTo(imgV.snp.right).offset(.scale*10)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*10)
        }
        let label2 = UILabel.xsLabel(size: .scale*14, fontName: .regular, color: #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), text: item.introduce)
        view.addSubview(label2)
        label2.snp.makeConstraints {
            $0.top.equalTo(label1.snp.bottom).offset(.scale*4)
            $0.left.equalTo(imgV.snp.right).offset(.scale*10)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*10)
        }
        let label3 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: "\(item.reservationCount)人已预约")
        view.addSubview(label3)
        label3.snp.makeConstraints {
            $0.bottom.equalTo(-.scale*3)
            $0.left.equalTo(imgV.snp.right).offset(.scale*10)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*10)
        }
        
        return view
    }
    
    func loadProgress(_ scroll: UIScrollView, top: inout CGFloat, item: XS_QueryUserCurriculumListM) {
        let label = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: "学习进度")
        scroll.addSubview(label)
        label.snp.makeConstraints {
            $0.top.equalTo(top)
            $0.left.equalTo(.scale*16)
        }
        
        let view = getProgress(item)
        view.frame = CGRect(x: .scale*16, y: top + .scale*40, width: .scale*343, height: .scale*104)
        scroll.addSubview(view)
        
        let tap = UITapGestureRecognizer()
        view.addGestureRecognizer(tap)
        tap.rx.event.asDriver()
            .drive(onNext: { _ in
                let vc = XS_KeChengVC()
                vc.id = "\(item.id)"
                XS_NVC.shared.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        
        top = top + .scale*64 + .scale*104
    }
    func getProgress(_ item: XS_QueryUserCurriculumListM) -> UIView {
        let view = UIView()
        view.layer.cornerRadius = .scale*4
        view.layer.backgroundColor = UIColor(red: 0.97, green: 0.97, blue: 0.97, alpha: 1.00).cgColor
        let imgV = UIImageView()
        imgV.layer.masksToBounds = true
        imgV.layer.cornerRadius = .scale*4
        imgV.sd_setImage(with: URL(string: item.curriculumImgUrl))
        imgV.frame = CGRect(x: .scale*12, y: .scale*12, width: .scale*112, height: .scale*80)
        view.addSubview(imgV)
        let label = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: item.curriculumName)
        view.addSubview(label)
        label.snp.makeConstraints {
            $0.top.equalTo(.scale*12)
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.right.equalTo(-.scale*12)
        }
        
        let text = NSMutableAttributedString()
        do {
            let attr = NSMutableAttributedString(string: "最近学习")
            attr.yy_font = .xsFont(name: .medium, .scale*12)
            attr.yy_color = #colorLiteral(red: 0.1716121137, green: 0.7779735923, blue: 0.675088048, alpha: 1)
            text.append(attr)
        }
        do {
            let attr = NSMutableAttributedString(string: "  剩余")
            attr.yy_font = .xsFont(name: .regular, .scale*12)
            attr.yy_color = #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1)
            text.append(attr)
        }
        do {
            let attr = NSMutableAttributedString(string: "\(item.lastDay)")
            attr.yy_font = .xsFont(name: .medium, .scale*12)
            attr.yy_color = #colorLiteral(red: 0.1716121137, green: 0.7779735923, blue: 0.675088048, alpha: 1)
            text.append(attr)
        }
        do {
            let attr = NSMutableAttributedString(string: "天 | 计划天数为\(item.planDay)天")
            attr.yy_font = .xsFont(name: .regular, .scale*12)
            attr.yy_color = #colorLiteral(red: 0.7227739692, green: 0.7475164533, blue: 0.7677033544, alpha: 1)
            text.append(attr)
        }
        let label2 = UILabel()
        label2.attributedText = text
        view.addSubview(label2)
        label2.snp.makeConstraints {
            $0.top.equalTo(.scale*58)
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
        }
        
        let view1 = UIView()
        view1.layer.cornerRadius = .scale*4
        view1.layer.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        view1.layer.masksToBounds = true
        view1.frame = CGRect(x: .scale*136, y: .scale*82, width: .scale*164, height: .scale*7)
        view.addSubview(view1)
        let view2 = UIView()
        view2.layer.cornerRadius = .scale*4
        view2.layer.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        view2.frame = CGRect(x: -.scale*164, y: 0, width: .scale*164, height: .scale*7)
        view1.addSubview(view2)
        view2.frame.origin.x = -.scale*164 * CGFloat(100-item.percentage)/100
        
        let label3 = UILabel.xsLabel(size: .scale*12, fontName: .medium, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: "\(item.percentage)%")
        view.addSubview(label3)
        label3.snp.makeConstraints{
            $0.centerY.equalTo(view1.snp.centerY)
            $0.left.equalTo(view1.snp.right).offset(.scale*8)
        }
        
        return view
    }
    
    func reLoadBanner(_ scroll: UIScrollView, top: inout CGFloat, dataModels: [XD_queryHomePageArea]) {
        
        for subItem in homePageAreaScroll.subviews {
            subItem.removeFromSuperview()
        }
        
        for (index, subModel) in dataModels.enumerated() {
            let btn = getBanner(subModel.imgUrl, text: subModel.areaName, index: CGFloat(index))
            btn.tag = index
            btn.addTarget(self, action: #selector(bannerBtnClick(btn:)), for: .touchUpInside)
            homePageAreaScroll.addSubview(btn)
        }
        let buttonP = .scale * 16
        let buttonW = (.screenWidth - buttonP * 5) / 4
        homePageAreaScroll.contentSize = CGSize.init(width: CGFloat(dataModels.count) * (buttonW + buttonP) + buttonP, height: .scale * 76)
    }
    
    @objc func bannerBtnClick(btn: UIButton) {
        let dModel = homePageAreaArr[btn.tag]
        if dModel.type == "builtIn" {
            switch dModel.typeRelation {
            case "zsbk":
                guard XS_Singleton.shared.infoModel != nil else {
                    XS_NVC.shared.toLogin()
                    return
                }
                let vc = XS_ZhengshuVC()
                vc.tags = self.channelArray.filter { $0.type != "nav" }
                self.navigationController?.pushViewController(vc, animated: true)
                break
            case "jytj":
                self.navigationController?.pushViewController(XS_ZhaopinVC(), animated: true)
                break
            case "vip":
                guard XS_Singleton.shared.infoModel != nil else {
                    XS_NVC.shared.toLogin()
                    return
                }
                let vc = XS_VipVC()
                vc.homeTop = self.channelArray.first
                vc.tags = self.channelArray.filter { $0.type != "nav" }
                self.navigationController?.pushViewController(vc, animated: true)
                break
            case "kcfl":
                self.navigationController?.pushViewController(XS_FenleiVC(), animated: true)
                break
            default:
                break
            }
        } else {
            let webVC = XS_WebPageVC()
            webVC.loadUrl(dModel.typeRelation)
            navigationController?.pushViewController(webVC, animated: true)
        }
    }
    
    func loadBanner(_ scroll: UIScrollView, top: inout CGFloat) {
        homePageAreaScroll.frame = CGRect.init(x: 0, y: top, width: .screenWidth, height: .scale * 76)
        scroll.addSubview(homePageAreaScroll)
        let btn1 = getBanner("icon_40px_证书百科", text: "证书百科", index: 0)
        let btn2 = getBanner("icon_40px_就业推荐备份", text: "就业推荐", index: 1)
        let btn3 = getBanner("icon_40px_vip备份", text: "VIP", index: 2)
        let btn4 = getBanner("icon_40px_课程分类", text: "课程分类", index: 3)
        homePageAreaScroll.addSubview(btn1)
        homePageAreaScroll.addSubview(btn2)
        homePageAreaScroll.addSubview(btn3)
        homePageAreaScroll.addSubview(btn4)
        top = top + .scale * 76 + .scale * 24
        
        btn1.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                guard XS_Singleton.shared.infoModel != nil else {
                    XS_NVC.shared.toLogin()
                    return
                }
                let vc = XS_ZhengshuVC()
                vc.tags = (self?.channelArray ?? []).filter { $0.type != "nav" }
                self?.navigationController?.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        btn2.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
//                guard XS_Singleton.shared.infoModel != nil else {
//                    XS_NVC.shared.toLogin()
//                    return
//                }
                self?.navigationController?.pushViewController(XS_ZhaopinVC(), animated: true)
            }).disposed(by: disposeBag)
        btn3.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                guard XS_Singleton.shared.infoModel != nil else {
                    XS_NVC.shared.toLogin()
                    return
                }
                let vc = XS_VipVC()
                vc.homeTop = self?.channelArray.first
                vc.tags = (self?.channelArray ?? []).filter { $0.type != "nav" }
                self?.navigationController?.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        btn4.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
//                guard XS_Singleton.shared.infoModel != nil else {
//                    XS_NVC.shared.toLogin()
//                    return
//                }
                self?.navigationController?.pushViewController(XS_FenleiVC(), animated: true)
            }).disposed(by: disposeBag)
    }
    func getBanner(_ img: String, text: String, index: CGFloat) -> UIButton {
        let button = XS_NoHighlightBtn()
        
        let buttonP = .scale * 16
        let buttonW = (.screenWidth - buttonP * 5) / 4
        
        button.frame = CGRect(x: buttonP + index * (buttonW + buttonP), y: 0, width: buttonW, height: .scale*76)
        let imgV = UIImageView()
        if img.hasPrefix("http") {
            imgV.sd_setImage(with: URL(string: img))
        } else {
            imgV.image = UIImage.init(named: img)
        }
        button.addSubview(imgV)
        imgV.snp.makeConstraints {
            $0.width.height.equalTo(.scale*48)
            $0.top.centerX.equalToSuperview()
        }
        let label = UILabel.xsLabel(size: .scale*14, fontName: .regular, color: #colorLiteral(red: 0.3531333804, green: 0.3753507137, blue: 0.4038540423, alpha: 1), alignment: .center, text: text)
        button.addSubview(label)
        label.snp.makeConstraints {
            $0.centerX.bottom.equalToSuperview()
        }
        return button
    }
}
